import Link from 'next/link';
import MarkDown from 'markdown-to-jsx';
import { useState } from 'react';
import { GetServerSidePropsContext } from 'next';
import { Avatar, Input, Button, Divider, message } from 'antd';
import { format } from 'date-fns';

import userStore from '@/store/userStore';
import requestInstance from '@/service/fetch';
import { prepareConnection } from '@/db';
import { Article } from '@/db/entity';
import { IArticle, IComment } from '@/pages/api';

import styles from './index.module.scss';

interface IProps {
  article: IArticle;
}

export const getServerSideProps = async (props: GetServerSidePropsContext) => {
  const articleId = props.params?.id;

  // 数据库连接相关的内容
  const db = await prepareConnection();
  const articleRepo = db.getRepository(Article);
  const article = await articleRepo.findOne({
    where: {
      id: articleId,
    },
    relations: ['user', 'comments', 'comments.user'],
  });

  if (article) {
    // 阅读次数 +1
    article.views = article?.views + 1;
    await articleRepo.save(article);
  }

  return {
    props: {
      article: JSON.parse(JSON.stringify(article)),
    },
  };
};

const ArticleDetail = (props: IProps) => {
  const { article } = props;
  const {
    user: { nickname, avatar, id },
  } = article;
  const [inputVal, setInputVal] = useState('');
  const [comments, setComments] = useState<IComment[]>(article.comments || []);
  const loginUserInfo = userStore(({ userInfo }) => userInfo);

  const handleComment = async () => {
    const result: any = await requestInstance.post('/api/comment/publish', {
      articleId: article?.id,
      content: inputVal,
    })

    if (result.code === 200) {
      message.success('发布成功')
      setComments(result.data)
      setInputVal('');
    } else {
      message.error(result.msg || '发布失败')
    }
  }

  return (
    <>
      <div className="content-layout">
        <h2 className={styles.title}>{article?.title}</h2>
        <div className={styles.user}>
          <Avatar src={avatar} size={50} />
          <div className={styles.info}>
            <div className={styles.name}>{nickname}</div>
            <div className={styles.date}>
              <div>
                {format(new Date(article?.update_time), 'yyyy-MM-dd hh:mm:ss')}
              </div>
              <div>阅读 {article?.views}</div>
              {Number(loginUserInfo?.userId) === Number(id) && (
                <Link href={`/editor/${article?.id}`}>编辑</Link>
              )}
            </div>
          </div>
        </div>
        <MarkDown className={styles.markdown}>{article?.content}</MarkDown>
      </div>
      <div className={styles.divider} />
      <div className='content-layout'>
        <div className={styles.comment}>
          <h3>评论</h3>
          {
            loginUserInfo?.userId ? (
              <div className={styles.enter}>
                <Avatar src={avatar} size={40} />
                <div className={styles.content}>
                  <Input.TextArea
                    placeholder="请输入评论"
                    rows={4}
                    value={inputVal}
                    onChange={(event) => setInputVal(event?.target?.value)}
                  />
                  <Button type="primary" onClick={handleComment}>
                    发表评论
                  </Button>
                </div>
              </div>
            ) : null
          }
          <Divider />
          <div className={styles.display}>
            {
              comments.map((comment: IComment) => (
                <div className={styles.wrapper} key={comment?.id}>
                  <Avatar src={comment?.user?.avatar} size={40} />
                  <div className={styles.info}>
                    <div className={styles.name}>
                      <div>{comment?.user?.nickname}</div>
                      <div className={styles.date}>
                        {format(
                          new Date(comment?.update_time as Date),
                          'yyyy-MM-dd hh:mm:ss'
                        )}
                      </div>
                    </div>
                    <div className={styles.content}>{comment?.content}</div>
                  </div>
                </div>
              ))
            }
          </div>
        </div>
      </div>
    </>
  );
};

export default ArticleDetail;
